package net;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.betwixt.expression.Context;
import org.apache.commons.betwixt.strategy.IdStoringStrategy;

import core.Dictionary;

/**
 * Acts as a map between XML ids and object references (and vice-versa).
 * Delegates id mappings for GameObjects to a separate Dictionary.
 */
public class ObjectStoringStrategy extends IdStoringStrategy
{
	public ObjectStoringStrategy(Dictionary dictionary) {
		this.dictionary = dictionary;
	}

	public String getReferenceFor(Context arg0, Object object) {
		if (object instanceof core.GameObject) {
			Integer id = dictionary.getId((core.GameObject)object);
			return id == null ? null : "go_" + id;
		}
		return objToIdMap.get(object);
	}

	public void setReference(Context arg0, Object object, String id) {
		if (!(object instanceof core.GameObject)) {
			idToObjMap.put(id, object);
			objToIdMap.put(object, id);
		}
	}

	public Object getReferenced(Context arg0, String id) {
		if (id.length() > 3 && "go_".equals(id.substring(0, 3)))
			return dictionary.getObject(Integer.parseInt(id.substring(3)));
		return idToObjMap.get(id);
	}

	public void reset() {
		objToIdMap.clear();
		idToObjMap.clear();
	}

	private final Map<String, Object> idToObjMap = new HashMap<String, Object>();
	private final Map<Object, String> objToIdMap = new HashMap<Object, String>();	
	private final Dictionary dictionary;
}